package com.ververica.cdc.guass.sink.jdbc;

import com.ververica.cdc.guass.sink.jdbc.derby.DerbyTestBase;
import com.ververica.cdc.guass.sink.jdbc.mysql.MySqlTestBase;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.Mockito;

import static org.mockito.Mockito.doReturn;

/**
 * Base class for JDBC test using DDL from {@link JdbcTestFixture}. It uses create tables before
 * each test and drops afterward.
 */
public abstract class JdbcTestBase implements MySqlTestBase {

    @BeforeEach
    public void before() throws Exception {
        JdbcTestFixture.initSchema(getMetadata());
    }

    @AfterEach
    public void after() throws Exception {
        JdbcTestFixture.cleanUpDatabasesStatic(getMetadata());
    }

    public static RuntimeContext getRuntimeContext(Boolean reused) {
        ExecutionConfig config = getExecutionConfig(reused);
        RuntimeContext context = Mockito.mock(RuntimeContext.class);
        doReturn(config).when(context).getExecutionConfig();
        return context;
    }

    public static RuntimeContext getRuntimeContext(JobID jobId) {
        RuntimeContext context = getRuntimeContext(false);
        doReturn(jobId).when(context).getJobId();
        return context;
    }

    public static ExecutionConfig getExecutionConfig(boolean reused) {
        ExecutionConfig config = new ExecutionConfig();
        if (reused) {
            config.enableObjectReuse();
        } else {
            config.disableObjectReuse();
        }
        return config;
    }

    public static <T> TypeSerializer<T> getSerializer(
            TypeInformation<T> type, Boolean objectReused) {
        return type.createSerializer(getExecutionConfig(objectReused));
    }
}
